NW | 26-SDC-Mar | Zabihollah Namazi | Sprint 2 | improve with caches#177
NW | 26-SDC-Mar | Zabihollah Namazi | Sprint 2 | improve with caches#177ZabihollahNamazi wants to merge 4 commits into
Conversation
| prev2 = 0 # fibonacci(0) | ||
| prev1 = 1 # fibonacci(1) | ||
|
|
||
| # Calculate upward to n | ||
| for _ in range(2, n + 1): | ||
| current = prev1 + prev2 | ||
| prev2 = prev1 | ||
| prev1 = current | ||
|
|
||
| return prev1 No newline at end of file |
There was a problem hiding this comment.
Replacing the recursive approach with an iterative one defeats the purpose of this exercise, which is to improve the performance of a recursive function using caching. Could you update the code while keeping the original recursive implementation?
There was a problem hiding this comment.
i have updated the code
thanks
| coins = [1, 2, 5, 10, 20, 50, 100, 200] | ||
|
|
||
| dp = [0] * (total + 1) | ||
|
|
||
| dp[0] = 1 | ||
|
|
||
| for coin in coins: | ||
| for i in range(coin, total + 1): | ||
| dp[i] += dp[i - coin] | ||
|
|
||
| return dp[total] No newline at end of file |
There was a problem hiding this comment.
Good job in finding out a faster approach to find the solution.
Could you also include an implementation that uses cache to speed up the original recursive implementation?
There was a problem hiding this comment.
i have updated the code
thanks
| fib_cache = {} | ||
| def fibonacci(n: int) -> int: | ||
| if n == 0: | ||
| return 0 |
There was a problem hiding this comment.
Note: We could also keep the cache as an attribute of the function.
|
Closing PR because the SDC run has finished. Feel free to re-open if you're still working on it. |
Hi! Could you please check my code?
I changed the Fibonacci and Making Change code. The old code was too slow and crashed with big numbers. I fixed it by using caching and loops so the code runs fast and passes all the big tests instantly.
Thank you!